package by.grsu.samusev.dao.impl;

import java.io.Serializable;
import java.util.List;

import by.grsu.samusev.entity.Request;
import by.grsu.samusev.table.RequestTable;

import com.epam.grsulab.webapi.dao.AbstractDao;

public class RequestDao  extends AbstractDao<RequestTable, Request> {

	/**
	 * 
	 */
	private static final long serialVersionUID = -6632696925113650798L;

	public RequestDao(String rootFolderPath) {
		super(rootFolderPath);
	}

	@Override
	public Long saveNew(final  Request newRequest) {
		
		Long nextId = getNextId();
		newRequest.setId(nextId);
		final RequestTable requestTable = deserializeFromXml();
		requestTable.getRows().add(newRequest);
		serializeToXml(requestTable);
		return nextId;
	}

	@Override
	public void update(final Request entity) {
				final RequestTable requestTable = deserializeFromXml();
				for (final Request row : requestTable.getRows()) {
					if (row.getId().equals(entity.getId())) {
					    row.setId(entity.getId());
						row.setVoyageId(entity.getVoyageId());
						row.setDate(entity.getDate());
						break;
					}
				}
				serializeToXml(requestTable);

			}

	@Override
	public Request get(final Serializable id) {
		final RequestTable requestTable = deserializeFromXml();
		for (final Request row : requestTable.getRows()) {
			if (row.getId().equals(id)) {
				return row;
			}
		}
		return null;
	}

	@Override
	public List<Request> getAll() {
		final RequestTable requestTable = deserializeFromXml();
		return requestTable.getRows();
	}

	@Override
	public void delete(final Serializable id) {
		final RequestTable requestTable = deserializeFromXml();
		Request toBeDeleted = null;
		for (final Request row : requestTable.getRows()) {
			if (row.getId().equals(id)) {
				toBeDeleted = row;
				break;
			}
		}
		requestTable.getRows().remove(toBeDeleted);
		serializeToXml(requestTable);
}

	@Override
	protected Class<RequestTable> getTableClass() {
		return RequestTable.class;
	}

}
